package com.youlai.boot.system.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.annotation.RepeatSubmit;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.result.PageResult;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.system.model.form.SpotRecordForm;
import com.youlai.boot.system.model.query.SpotRecordQuery;
import com.youlai.boot.system.model.vo.SpotRecordExcelVO;
import com.youlai.boot.system.model.vo.SpotRecordVO;
import com.youlai.boot.system.service.SpotRecordService;
import com.youlai.boot.util.ExcelUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import java.util.List;

/**
 * 出票数据前端控制层
 *
 * @author lwb
 * @since 2025-06-29 22:35
 */
@Tag(name = "出票数据接口")
@RestController
@RequestMapping("/api/v1/spotRecords")
@RequiredArgsConstructor
public class SpotRecordController {

    private final SpotRecordService spotRecordService;

    //@Operation(summary = "出票数据分页列表")
    @GetMapping("/page")
    @PreAuthorize("@ss.hasPerm('system:spotRecord:query')")
    public PageResult<SpotRecordVO> getSpotRecordPage(SpotRecordQuery queryParams ) {
        IPage<SpotRecordVO> result = spotRecordService.getSpotRecordPage(queryParams);
        return PageResult.success(result);
    }

    @Operation(summary = "导出出票数据")
    @GetMapping("/export")
    @PreAuthorize("@ss.hasPerm('system:spotRecord:word')")
    public void export(SpotRecordQuery queryParams, HttpServletResponse response) throws IOException {

        List<SpotRecordExcelVO> list = spotRecordService.export(queryParams);
        InputStream resourceAsStream = ExcelUtils.class.getClassLoader().getResourceAsStream("excel-template/spotRecord.xlsx");
        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(String.format("出票数据_%s.xlsx", LocalDate.now()), StandardCharsets.UTF_8));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).sheet().doFill(list);
    }

    //@Operation(summary = "出票数据统计")
    @GetMapping("/count")
    @PreAuthorize("@ss.hasPerm('system:spotRecord:query')")
    public Result<List<SpotRecordForm>> count(SpotRecordQuery queryParams) {
        return Result.success(spotRecordService.getCount(queryParams));
    }

    @Operation(summary = "新增出票数据")
    @PostMapping
    @PreAuthorize("@ss.hasPerm('system:spotRecord:add')")
    @RepeatSubmit(expire = 3)
    @Log(value = "新增出票数据", module = LogModuleEnum.OTHER)
    public Result<String> saveSpotRecord(@RequestBody @Valid SpotRecordForm formData ) {
        return Result.success(spotRecordService.saveSpotRecord(formData));
    }

    //@Operation(summary = "获取出票数据表单数据")
    @GetMapping("/{id}/form")
    @PreAuthorize("@ss.hasPerm('system:spotRecord:edit')")
    public Result<SpotRecordForm> getSpotRecordForm(
        @Parameter(description = "出票数据ID") @PathVariable Long id
    ) {
        SpotRecordForm formData = spotRecordService.getSpotRecordFormData(id);
        return Result.success(formData);
    }

    @Operation(summary = "修改出票数据")
    @PutMapping(value = "/{id}")
    @PreAuthorize("@ss.hasPerm('system:spotRecord:edit')")
    @Log(value = "修改出票数据", module = LogModuleEnum.OTHER)
    @RepeatSubmit(expire = 3)
    public Result<Void> updateSpotRecord(
            @Parameter(description = "出票数据ID") @PathVariable Long id,
            @RequestBody @Validated SpotRecordForm formData
    ) {
        boolean result = spotRecordService.updateSpotRecord(id, formData);
        return Result.judge(result);
    }

    @Operation(summary = "删除出票数据")
    @DeleteMapping("/{ids}")
    @PreAuthorize("@ss.hasPerm('system:spotRecord:delete')")
    @Log(value = "删除出票数据", module = LogModuleEnum.OTHER)
    public Result<Void> deleteSpotRecords(
        @Parameter(description = "出票数据ID，多个以英文逗号(,)分割") @PathVariable String ids
    ) {
        boolean result = spotRecordService.deleteSpotRecords(ids);
        return Result.judge(result);
    }
}
